<?php
/**
 * Created by PhpStorm.
 * User: moquan
 * Date: 2018/7/11
 * Time: 18:39
 */

namespace app\lib\wx;


use think\Cache;
use think\Exception;

class AccessToken {
    const TOKENURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /*
    * 获取accessToken
    * */
    public function getAccessToken( $refresh = false ){
        //从缓存里取
        $cached = cache('access_token');
        //是否强制刷新
        //缓存不存在
        if ($refresh || empty( $cached )) {
            //获取accessToken
            $token = $this->getAccessTokenFromServer();
            //存入缓存
            Cache::set( 'access_token', $token['access_token'], $token['expires_in'] - 1500 );
            return $token['access_token'];
        }
        return $cached;
    }

    /**
     * 取accessToken
     */
    public function getAccessTokenFromServer()
    {
        $url = config('wx.access_token_url');
        $url = sprintf($url, $this->appID, $this->appSecret );
        $token = curl_get( $url, true );
        if (empty($token['access_token'])) {
            $err = json_encode( $token, JSON_UNESCAPED_UNICODE );
            $this->recordErrorLog( $err );
            throw new Exception( 'Request AccessToken fail. response: '.$err );
        }
        return $token;

    }
}